<template>
    <div class="layout">
        <!-- 头部区域 -->
        <header class="layout__header">
            <Header :system-name="config.systemName" :logo-src="config.logoSrc" :user-name="config.userName"
                :user-avatar="config.userAvatar" :user-organization="config.userOrganization"
                @personal-settings="handlePersonalSettings" @logout="handleLogout" />
        </header>
        <div class="layout__body">
            <!-- 侧边栏组件 -->
            <div class="layout__bode-left" @mouseenter="handleMenuMouseEnter" @mouseleave="handleMenuMouseLeave">
                <div class="layout_Collapsed-icon" @click="toggleSidebar" :title="sidebarCollapsed ? '展开菜单' : '收起菜单'"
                    :class="{ 'layout_Collapsed-Filed': sidebarCollapsed }" @mouseenter="handleIconMouseEnter"
                    @mouseleave="handleIconMouseLeave"
                    v-html="sidebarCollapsed ? SIDEBAR_EXPAND_ICON : SIDEBAR_COLLAPSE_ICON" :style="menuCollapsedStyle">
                </div>
                <Sidebar :collapsed="sidebarCollapsed" :menuMouseEnter="isMenuMouseEnter"
                    @menu-select="handleMenuSelect">
                </Sidebar>
            </div>
            <div class="layout__bode-line" @mouseenter="handleLineMouseEnter"></div>
            <div class="layout__bode-right">
                <!-- 主体内容区域 - 使用RouterView -->
                <main class="layout__main">
                    <RouterView />
                </main>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import Sidebar from '@/components/pc/Sidebar.vue'
import Header from '@/components/pc/Header.vue'
import { useRoute, useRouter } from 'vue-router'
import { ROUTE_NAMES } from '@/constants/routes.js'
const route = useRoute()
const router = useRouter()

import {
    SYSTEM_NAME,
    LOGO_SRC,
    DEFAULT_USER_NAME,
    DEFAULT_USER_AVATAR,
    DEFAULT_USER_ORGANIZATION
} from '@/constants/layout.js'
import { SIDEBAR_COLLAPSE_ICON, SIDEBAR_EXPAND_ICON } from '@/constants/svg.js'
import { navigateToMenuByConfig, setBrowserTitle } from '@/service/funcMenuService'
import userProfileService from '@/service/userProfileService'
import { eventBus } from '@/service/eventService'
import { ROUTES } from '@/constants/routes.js'
import { changeTheme,notifyIframesThemeChange } from '@/service/commonService'
// 侧边栏收起状态
const sidebarCollapsed = ref(false)

const isMenuMouseEnter = ref(false)

// 使用 reactive 创建配置对象
const config = reactive({
    systemName: SYSTEM_NAME,
    logoSrc: LOGO_SRC,
    userName: DEFAULT_USER_NAME,
    userAvatar: DEFAULT_USER_AVATAR,
    userOrganization: DEFAULT_USER_ORGANIZATION
})


// 切换侧边栏状态的方法
const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
}

const menuCollapsedStyle = computed(() => {
    if (sidebarCollapsed.value && isMenuMouseEnter.value) {
        return { left: '247px', transition: 'left 0.3s ease' }
    }
    if (!sidebarCollapsed.value) {
        return { right: '-11px', transition: 'left 0.3s ease' }
    }
    return {
        left: '0px',
        transition: 'left 0.3s ease'
    };
})

const isIconHover = ref(false)

const handleMenuMouseEnter = () => {
    if (sidebarCollapsed.value && !isIconHover.value) {
        isMenuMouseEnter.value = true
    }
}

const handleMenuMouseLeave = () => {
    if (sidebarCollapsed.value) {
        isMenuMouseEnter.value = false
    }
}

const handleIconMouseEnter = () => {
    isIconHover.value = true
    if (sidebarCollapsed.value) {
        return
    }
    isMenuMouseEnter.value = false
}

const handleIconMouseLeave = () => {
    isIconHover.value = false
}

const handleLineMouseEnter = () => {
    if (sidebarCollapsed.value) {
        isMenuMouseEnter.value = true
    }
}

const handleMenuSelect = (menu) => {

    navigateToMenuByConfig(menu.ID)
}



// 处理个人设置点击
const handlePersonalSettings = () => {
    console.log('个人设置被点击')
    // 跳转到个人设置页面
    router.push({ name: ROUTE_NAMES.PC_PERSONAL_SETTINGS })
}

// 处理退出点击
const handleLogout = () => {
    Funcs.Confirm('提示信息', '确定退出吗?', async function () {
        try {
            // 调用退出登录接口
            const result = await userProfileService.logout();
            Funcs.Notify('提示', '退出成功', 'success');
            router.push({ name: ROUTE_NAMES.LOGIN })
        } catch (error) {
            console.error('退出登录异常:', error);
        }
    }, function () {
        console.log('取消退出登录');
    }, 'tr', { type: 'warning' })
}

// 处理浏览器标题更新
const handleBrowserTitleUpdate = (router) => {
    if (router.path == ROUTES.HARDCODE_WEB_BLANK) {
        setBrowserTitle(SYSTEM_NAME)
        return
    }
    if (router.path == ROUTES.HARDCODE_WEB_ERROR404) {
        setBrowserTitle('404')
        return
    }
    if(router.path == ROUTES.HARDCODE_WEB_PERSONAL_SETTINGS){
        setBrowserTitle(`个人设置-${SYSTEM_NAME}`)
        return
    }
}

// 标志位，防止重复注册iframe点击监听
let isIframeClickListenerRegistered = false

const handleIframeClick = () => {
    if (isIframeClickListenerRegistered) {
        return
    }

    window.addEventListener("blur", () => {
        if (document.activeElement && document.activeElement.tagName === "IFRAME") {
            eventBus._emit('iframeClickEvent')
        }
    })

    isIframeClickListenerRegistered = true
}


// 初始化事件监听器
const initEventListeners = () => {
    // 监听到界面加载完再注册iframe点击监听
    eventBus.on('pageLoadedEvent', () => {
        handleIframeClick()
        notifyIframesThemeChange()
    })


    eventBus.on('changeUserProfileEvent', (profileKey, profileValue) => {
        userProfileService.saveUserProfile(profileKey, profileValue, false)
        if (profileKey == 'wrp_theme') {
            changeTheme(profileValue,false)
        }
    })


}

// 在组件挂载时初始化事件监听
onMounted(() => {
    initEventListeners()
})

watch(() => route, handleBrowserTitleUpdate, { immediate: true, deep: true })


</script>
<style lang="scss">
.layout_Collapsed-icon {
    .menu {
        color: #999999;
    }

    .line {
        stroke: #fff;
    }

    .border {
        stroke: #eeeeee;
    }
}

.layout_Collapsed-icon:hover {


    svg {
        box-shadow: rgba(9, 30, 66, 0.08) 3px 7px 5px 4px, inset rgba(9, 30, 66, 0.08) 9px 6px 13px 7px;
    }

    .menu {
        color: #fff;
    }

    .border {
        stroke: rgba(var(--theme-color-base), 0.8);
    }

    .line {
        stroke: rgba(var(--theme-color-base), 0.8);
    }

}
</style>
<style scoped lang="scss">
.layout_Collapsed-icon.layout_Collapsed-Filed {
    opacity: 1;
}

.layout_Collapsed-icon:hover {
    opacity: 1;
    color: rgba(var(--theme-color-base), 0.8);
}

.layout__bode-left {
    position: relative;
    height: calc(100vh - var(--layout-height));
}

.layout__bode-right {
    flex: 1;
    display: flex;
}

.layout__bode-line {
    width: 8px;
    height: calc(100vh - var(--layout-height));
}

/* BEM命名规范的CSS样式 */
.layout {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    width: 100vw;
}

/* 头部样式 - 固定高度56px */
.layout__header {
    height: var(--layout-height);
    background: var(--theme-color-background);
    position: sticky;
    top: 0;
    z-index: 1000;
}

.layout__header-content {
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 16px;
}

/* 布局主体 */
.layout__body {
    height: calc(100vh - var(--layout-height));
    display: flex;
    flex: 1;
}

/* 主体内容区域 */
.layout__main {
    flex: 1;
    min-height: calc(100vh - var(--layout-height));
    height: calc(100vh - var(--layout-height));
    max-height: calc(100vh - var(--layout-height));
    overflow-y: hidden;
}





.layout__bode-left:hover .layout_Collapsed-icon {
    opacity: 1;
}

.layout__bode-line:hover .layout_Collapsed-icon {
    opacity: 1;
}

.layout_Collapsed-icon {
    height: 68px;
    color: #fff;
    z-index: 2;
    position: absolute;
    border: none;
    cursor: pointer;

    bottom: 50%;
    --triangle-color: #44546f;
    border-top-right-radius: 2px;
    border-bottom-right-radius: 2px;
    opacity: 0;
    width: 13px;


}
</style>